import { Link } from 'react-router-dom';
import { cn, getImageUrl } from '@/lib/utils';
import { useLatestNews } from '@/hooks/useNews';
import { News } from '@/types';

// 默认新闻数据（作为后备）
const defaultNews: News[] = [
  {
    id: 1,
    title: '我公司荣获"2023年度最佳环境咨询机构"称号',
    excerpt: '近日，在省环境保护产业协会年度评选中，我公司凭借专业的技术服务和卓越的项目业绩，荣获"2023年度最佳环境咨询机构"称号。',
    content: '',
    cover_image: 'https://space.coze.cn/api/coze_space/gen_image?image_size=square&prompt=environmental+award+ceremony+with+green+certificate%2C+professional+photography%2C+high+quality&sign=036cb6fbe3b49bf4d868d99a2b19c45a',
    category: '公司新闻',
    author: '管理员',
    is_published: true,
    is_featured: true,
    view_count: 0,
    published_at: '2023-12-15T00:00:00Z',
    created_at: '2023-12-15T00:00:00Z'
  },
  {
    id: 2,
    title: '城市污水处理厂提标改造项目顺利通过验收',
    excerpt: '由我公司提供技术支持的市污水处理厂提标改造项目顺利通过环保部门验收，出水水质达到地表水IV类标准。',
    content: '',
    cover_image: 'https://space.coze.cn/api/coze_space/gen_image?image_size=square&prompt=modern+wastewater+treatment+plant+with+water+recycling+system%2C+professional+photography%2C+high+quality&sign=c8520e078070e9ee01466a01c370f88d',
    category: '项目动态',
    author: '技术部',
    is_published: true,
    is_featured: false,
    view_count: 0,
    published_at: '2023-11-28T00:00:00Z',
    created_at: '2023-11-28T00:00:00Z'
  },
  {
    id: 3,
    title: '公司举办"双碳目标与企业可持续发展"专题研讨会',
    excerpt: '为帮助企业应对"双碳"目标挑战，我公司成功举办专题研讨会，邀请业内专家共同探讨企业低碳转型路径与实践方案。',
    content: '',
    cover_image: 'https://space.coze.cn/api/coze_space/gen_image?image_size=square&prompt=environmental+sustainability+seminar+with+experts+and+audience%2C+professional+photography%2C+high+quality&sign=82617fbf85b37b8e3ab47620f14e6e11',
    category: '行业动态',
    author: '市场部',
    is_published: true,
    is_featured: false,
    view_count: 0,
    published_at: '2023-10-10T00:00:00Z',
    created_at: '2023-10-10T00:00:00Z'
  }
];

// 格式化日期的辅助函数
const formatDate = (dateString: string) => {
  const date = new Date(dateString);
  return date.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit'
  });
};

export default function NewsSection() {
  // 获取最新新闻数据
  const { data: latestNews, isLoading, error } = useLatestNews(3);

  // 使用API数据或默认数据
  const newsItems = latestNews && latestNews.length > 0 ? latestNews : defaultNews;

  return (
    <section className="py-20">
      <div className="container mx-auto px-4">
        <div className="flex flex-col md:flex-row justify-between items-start md:items-end mb-12">
          <div>
            <h2 className="text-3xl md:text-4xl font-bold text-gray-800 mb-4">新闻动态</h2>
            <div className="w-20 h-1 bg-blue-600"></div>
          </div>
          <Link
            to="/news"
            className="mt-4 md:mt-0 inline-flex items-center text-blue-600 font-medium hover:text-blue-800 transition-colors"
          >
            查看全部新闻 <i className="fa-solid fa-arrow-right ml-2"></i>
          </Link>
        </div>

        {/* 加载状态 */}
        {isLoading && (
          <div className="flex justify-center items-center py-12">
            <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600"></div>
            <span className="ml-2 text-gray-600">加载新闻...</span>
          </div>
        )}

        {/* 错误状态 */}
        {error && !isLoading && (
          <div className="bg-red-50 border border-red-200 rounded-lg p-6 text-center">
            <p className="text-red-600">加载新闻失败，显示默认内容</p>
          </div>
        )}

        {/* 新闻列表 */}
        {!isLoading && (
          <div className="grid md:grid-cols-3 gap-8">
            {newsItems.map((item) => (
              <div
                key={item.id}
                className="bg-white rounded-lg overflow-hidden shadow-md hover:shadow-xl transition-shadow duration-300 border border-gray-100"
              >
                <div className="relative h-48 overflow-hidden">
                  <img
                    src={getImageUrl(item.cover_image)}
                    alt={item.title}
                    className="w-full h-full object-cover transition-transform duration-500 hover:scale-110"
                    onError={(e) => {
                      const target = e.target as HTMLImageElement;
                      target.src = getImageUrl(null);
                    }}
                  />
                  <div className="absolute top-4 left-4 bg-blue-600 text-white text-sm font-medium px-3 py-1 rounded-full">
                    {formatDate(item.published_at)}
                  </div>
                  {item.is_featured && (
                    <div className="absolute top-4 right-4 bg-red-500 text-white text-xs font-medium px-2 py-1 rounded-full">
                      置顶
                    </div>
                  )}
                </div>
                <div className="p-6">
                  <div className="flex items-center mb-2">
                    <span className="text-xs text-blue-600 bg-blue-50 px-2 py-1 rounded-full">
                      {item.category}
                    </span>
                    <span className="text-xs text-gray-500 ml-2">
                      浏览 {item.view_count}
                    </span>
                  </div>
                  <h3 className="text-xl font-semibold text-gray-800 mb-3 hover:text-blue-600 transition-colors">
                    <Link to={`/news/${item.id}`}>{item.title}</Link>
                  </h3>
                  <p className="text-gray-600 mb-4 line-clamp-3">
                    {item.excerpt || '暂无摘要...'}
                  </p>
                  <div className="flex justify-between items-center">
                    <Link
                      to={`/news/${item.id}`}
                      className="inline-flex items-center text-blue-600 text-sm font-medium hover:text-blue-800 transition-colors"
                    >
                      阅读全文 <i className="fa-solid fa-angle-right ml-1"></i>
                    </Link>
                    <span className="text-xs text-gray-400">
                      {item.author}
                    </span>
                  </div>
                </div>
              </div>
            ))}
          </div>
        )}
      </div>
    </section>
  );
}